/**
 * 项目名称：MSH
 * 包名称：com.mt.common.sys.dao
 * 文件名称：UserDaoImpl.java
 */
package com.mt.system.daoImpl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.mt.system.dao.UserDao;
import com.mt.system.domain.User;


/**
 * 类名称：UserDaoImpl
 * 类描述：
 * 创建人： 马腾
 * 创建时间：2012-10-17 下午10:58:54
 */
@Repository
public class UserDaoImpl implements UserDao {

	@PersistenceContext
	protected EntityManager entityManager;
	
	@Override
	public User addUser(User user) {
		entityManager.persist(user);
		return user;
	}

	@Override
	public void deleteUser(User user) {
//		String hql = "delete from User u where u.id = :id";
//		Query query = entityManager.createQuery(hql);
//		query.setParameter("id", user.getId());
//		query.executeUpdate();
		entityManager.remove(user);
	}

	@Override
	public void updateUser(User user) {
		entityManager.merge(user);
	}
	
	@Override
	public User getUserById(String id) {
		return entityManager.find(User.class, id);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<User> getUsers(User userDto) {
		String hql = "FROM User u where u.status = 1 and u.name != 'admin'";
		Query query = entityManager.createQuery(hql);
		return query.getResultList();
	}

	@Override
	public int getCount(User userDto) {
		String eql = "select count(*) from User u where u.status = 1 and u.name != 'admin'";
		Query query = entityManager.createQuery(eql);
		Long count = (Long) query.getSingleResult();
		return count == null ? 0 : count.intValue();
	}

	@Override
	public User getUserByName(String name) {
		String hql = "FROM User u where u.name = :name and u.status = 1";
		Query query = entityManager.createQuery(hql);
		query.setParameter("name", name);
		try {
			return (User) query.getSingleResult();
		} catch (NoResultException  e) {
			return null;
		}
	}
}
